<?php

/**
 * @file   admin.php
 * @date   2017-11-15 15:22:57
 * @author huwhis<huuwhois>
 * @version   0.0.1
 */
namespace app\admin\controller;

use app\admin\model\AdminUser as UserModel;
use think\Request;

class AdminUser extends Base
{
    protected $model;
    protected $request;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        
        $this->request = $request;

        $this->model = new UserModel();
    }

    public function index()
    {
        $field = 'id, username, role_id, pen_name, email, ctime, login_time, login_ip, status';

        $data = $this->model->field($field)->select();

        $this->assign("data", $data);

        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPOST()) {
            $param = $this->request->param();

            $role_id = isset($param['role_id']) ? intval($param['role_id']) : "";
            $username = isset($param['username']) ? trim($param['username']) : "";
            
            if ($username == '' || $role_id == '') {
                $this->error("用户名 or 角色 不能为空");
            }
            
            $info = $this->model->where('username', $username)->find();
            
            if ($info) {
                $this->error("该账户已存在,请使用其他用户名");
            }
            
            $password = isset($param['password']) ? md5(trim($param['password'])) : md5(config('pwd'));
            $pen_name = isset($param['pen_name']) ? trim($param['pen_name']) : "";
            $email = isset($param['email']) ? trim($param['email']) : "";
            $description = isset($param['description']) ? trim($param['description']) : "";
            $ctime = time();

            try {
                $this->model->save([
                    "username" => $username,
                    "role_id" => $role_id,
                    "password" => $password,
                    "pen_name" => $pen_name,
                    "email" => $email,
                    "description" => $description,
                    "ctime" => $ctime,
                ]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }
            $this->success('添加成功', '/admin_user/index');
        } else {
            $admin_roles = model('admin_role')->where('status', 1)->order('id')->column('id, name');

            $this->assign("admin_roles", $admin_roles);
            return $this->fetch();
        }
    }

    public function edit($id)
    {
        $data = $this->model->find($id);
        if ($this->request->isPOST()) {
            $param = $this->request->param();

            $role_id = isset($param['role_id']) ? intval($param['role_id']) : 0;
            $username = isset($param['username']) ? trim($param['username']) : "";
            
            if ($username == '' || $role_id == 0) {
                $this->error("用户名 or 角色 不能为空");
            }

            $info = $this->model->where('username', $username)->where('id', '<>', $id)->find();
            
            if ($info) {
                $this->error("该账户已存在,请使用其他用户名");
            }

            $pen_name = isset($param['pen_name']) ? trim($param['pen_name']) : "";
            $email = isset($param['email']) ? trim($param['email']) : "";
            $description = isset($param['description']) ? trim($param['description']) : "";
            $status = isset($param['status']) ? intval($param['status']) : 1;

            try {
                $this->model->save([
                    "username" => $username,
                    "role_id" => $role_id,
                    "pen_name" => $pen_name,
                    "email" => $email,
                    "description" => $description,
                    'status' => $status,
                ], ['id' => $id]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }
            $this->success('修改成功', '/admin_user/index');
        }
        $admin_roles = model('admin_role')->where('status', 1)->order('id')->column('id, name');

        $this->assign("admin_roles", $admin_roles);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * (批量)删除管理员
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $id = $param['id'];

            if (is_array($id)) {
                if (in_array('1', $id)) {
                    return ['code' => 0, 'msg' => '超级管理员无法删除'];
                }
                if (in_array($this->uid, $id)) {
                    return ['code' => 0, 'msg' => '当前用户无法删除'];
                }
            } else {
                if ($id == 1) {
                    return ['code' => 0, 'msg' => '超级管理员无法删除'];
                }
                if ($id == $this->uid) {
                    return ['code' => 0, 'msg' => '当前用户无法删除'];
                }
            }
            if ($this->model->destroy($id)) {
                return ['code' => 2, 'msg' => '删除成功'];
            } else {
                return ['code' => 0, 'msg' => config('msg.1002')];
            }
        }
    }

    /**
     * 停用 or 启用管理员
     */
    public function status()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id');
            $value = $this->request->param('value');
            if ($id == 1) {
                $this->error('超级管理员禁止停用');
            }

            if ($id == session('uid')) {
                $this->error('当前登录用户无法停用');
            }

            if ($this->model->save(['status' => $value], ['id' => $id])) {
                return ['code' => 2, 'msg' => '操作成功'];
            } else {
                return ['code' => 0, 'msg' => '操作失败'];
            }
        }
    }

    /**
     * 修改密码 function
     *
     * @return void
     */
    public function modifyPwd()
    {
        if ($this->request->isAjax()) {
            if ($this->uid != 1) {
                $this->error('您无权进行此项操作');
            }

            $id = input('post.id');
            $pwd = md5(config('pwd'));

            $result = $this->model->save(['password' => $pwd], ['id' => $id]);
            
            if ($result === false) {
                $this->error(config('msg.1001') . ', 请稍后重试');
            }

            return ['code' => 2, 'msg' => config('msg.1001')];
        } elseif ($this->request->isPost()) {
            $info = $this->model->field('password')->find($this->uid);
            $pwd = $info->password;
            $oldpwd = md5(trim(input('post.oldpassword')));
            $newpwd = md5(trim(input('post.newpassword')));
            $repwd = md5(trim(input('post.repassword')));

            if ($pwd != $oldpwd) {
                $this->error('原密码不正确');
            }

            if ($newpwd != $repwd) {
                $this->error('两次新密码不一致，请核查');
            }

            $info->password = $newpwd;

            /**if ($info->save()) 当新旧密码一样时报错
             *
             * 改为以下代码，新旧密码一样也可改
             */

            $result = $info->save();

            if ($result !== false) {
                session(null);

                $this->success("修改成功,请重新登陆", '/logout');
            } else {
                $this->error('修改失败，请稍后重试');
            }
        } else {
            return $this->fetch();
        }
    }

    /**
     * 个人信息 笔名与邮箱的更改
     *
     * @return void
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $value = $param['value'];
            $field = $param['field'];

            try {
                $this->model->save([$field => $value], ['id' => $this->uid]);
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:" . $msg);
            }

            return ['code'=>2, 'msg'=>'修改成功'];
        }
    }
}
